﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using KaiXin.DTO.Tycoon;
using System.Threading;

namespace KaiXin.DAL.XML
{
    public class OrdersDAL : Persistence<Orders>
    {
        public override string XML_FILE_PATH
        {
            get
            {
                return "c:\\ORDERS.XML";
            }
        }

        protected override XElement SearchItem(Orders order)
        {
            var s = from el in _xd.Element("root").Elements("order") where el.Element("gid").Value == order.GoodsID && el.Element("email").Value == order.Email && el.Element("sell").Value == (order.IsSell ? "1" : "0" ) select el;
            return s.FirstOrDefault();
        }

        public override void AddItem(Orders order)
        {
            _xd.Element("root").Add(new XElement("order"
               , new XElement("email", order.Email)
               , new XElement("pwd", order.Password)
               , new XElement("gid", order.GoodsID)
               , new XElement("price", order.Price)
               , new XElement("sell", order.IsSell ? "1" : "0")
               ));
        }

        public override void InitItem(Orders order)
        {
            throw new NotImplementedException();
        }

        public override void DeleteItem(Orders item)
        {
            XElement el = SearchItem(item);
            if (el!=null)
            {
                el.Remove();
            }
        }

        public override List<Orders> GetAllItem()
        {
            List<Orders> list = new List<Orders>();
            foreach (var item in _xd.Element("root").Elements("order"))
            {
                list.Add(Exchange(item));
            }
            return list;
        }

        private Orders Exchange(XElement el)
        {
            Orders order = new Orders();
            order.Email = el.Element("email").Value;
            order.GoodsID = el.Element("gid").Value;
            order.IsSell = el.Element("sell").Value == "1";
            order.Password = el.Element("pwd").Value;
            order.Price = long.Parse(el.Element("price").Value);
            return order;
        }
        /// <summary>
        /// xml文件被修改后将重新加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void XML_File_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
            bool f = true;
            while (f)
            {
                try
                {
                    _xd = XDocument.Load(XML_FILE_PATH);
                    f = false;
                }
                catch (System.IO.IOException)
                {
                    Thread.Sleep(500);
                }
              
            }
            
        }
    }
}
